package com.sanpu.kxe.business.trade.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.provider.ICardProvider;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.provider.IMainProvider;
import com.sanpu.kxe.business.trade.bean.WithdrawDictinaryOutput;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.contract.WithdrawContract;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.utils.CommonUtils;
import com.sanpu.kxe.jump.eventbus.RefreshBalanceEvent;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.utils.DateUtils;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：提现
 * Created by 薛勇军 on 2018/8/9.
 */

public class WithdrawPresenter implements WithdrawContract.Presenter {

    private WithdrawContract.View mView;

    private CompositeSubscription mSubscription;

    private String mAccountName;

    private BigDecimal mMaxWithdrawLimit, mMinWithdrawLimit, mAmount, mBalance;

    private String beforeEdit;
    //是否重置了EditText的内容
    private boolean resetText = false;

    public WithdrawPresenter(WithdrawContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void initViewData(String withdrawMoney) {
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null) {
            mAccountName = centerOutput.getUserName();
            if (!TextUtils.isEmpty(withdrawMoney)) {
                mBalance = new BigDecimal(withdrawMoney);
            } else {
                mBalance = centerOutput.getBalance();
            }
            final String authenState = centerOutput.getChkSts();
            String remark = null;
            if (TextUtils.equals(CommonConfig.AUTHEN_NOTSUB, authenState)) {
                remark = "请先进行实名认证";
            } else if (TextUtils.equals(CommonConfig.AUTHEN_AUDIT, authenState)) {
                remark = "实名认证正在审核中，请稍候";
            } else if (TextUtils.equals(CommonConfig.AUTHEN_NOPASS, authenState)) {
                remark = "实名认证审核失败，请重新提交审核";
            }

            if (!TextUtils.isEmpty(remark)) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext()).content(remark);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (!TextUtils.equals(CommonConfig.AUTHEN_AUDIT, authenState)) {
                            IMainProvider provider = PublicProviderUtil.getProvider(IMainProvider.class);
                            if (provider != null) {
                                provider.openCertificationActivity(mView.getContext(), false);
                            }
                        }
                        ((Activity) mView.getContext()).finish();
                    }
                });
                dialog.show();
                return;
            }
            UserConfigOutput configOutput = CacheManage.getInstance().getCache(CacheModel.USER_CONFIG);
            if (configOutput == null || !TextUtils.equals("1", configOutput.getPayPwd())) {
                GlobalDialog dialog = new GlobalDialog(mView.getContext()).headerIcon(R.drawable.img_warm_prompt)
                        .title("温馨提示")
                        .content("提现前必须设置支付密码");
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        IMainProvider mainProvider = PublicProviderUtil.getProvider(IMainProvider.class);
                        if (mainProvider != null) {
                            mainProvider.openSetPayPwdOneActivity(mView.getContext(), true);
                        }
                    }
                });
                dialog.show();
                return;
            }

            withdrawDictinary();
        }
    }

    @Override
    public void onComfirmClick(BankInfoOutput output, String inputMoney) {
        if (output == null || TextUtils.isEmpty(output.getBankId())) {
            ToastUtil.showTextViewPrompt("请选择银行卡");
            return;
        }
        if (TextUtils.isEmpty(inputMoney)) {
            ToastUtil.showTextViewPrompt("请填写提现金额");
            return;
        }
        if (mAmount.doubleValue() <= 0) {
            ToastUtil.showTextViewPrompt("余额不足！");
            return;
        }
        Double amt;
        try {
            amt = Double.parseDouble(inputMoney);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            ToastUtil.showTextViewPrompt("余额输入不正确！");
            return;
        }
        if (mAmount.doubleValue() < amt) {
            ToastUtil.showTextViewPrompt("不能超过余额！");
            mView.setInputMoney(mAmount.toPlainString());
            return;
        }
        if (mMinWithdrawLimit != null && amt < mMinWithdrawLimit.doubleValue()) {
            ToastUtil.showTextViewPrompt("提现金额不能小于￥"+mMinWithdrawLimit);
            mView.setInputMoney(mMinWithdrawLimit.toPlainString());
            return;
        }
        if (mMaxWithdrawLimit != null && amt > mMaxWithdrawLimit.doubleValue()) {
            ToastUtil.showTextViewPrompt("提现金额不能大于￥" + mMaxWithdrawLimit);
            mView.setInputMoney(mMaxWithdrawLimit.toPlainString());
            return;
        }
        mView.onRightCallBack();
    }

    @Override
    public void withdraw(final String inputMoney, String payPwd, String bankId) {
        mView.showLoadingDialog(false);
        Subscription subscription = TradeModel.getInstance()
                .userWithdraw(inputMoney, payPwd, mAccountName, bankId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        TradeOpenProvider.getInstance().openWithdrawDetailsActivity(mView.getContext(),
                                inputMoney, false, e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {
                        mView.dismissLoadingDialog();
                        EventBus.getDefault().post(new RefreshBalanceEvent());
                        TradeOpenProvider.getInstance().openWithdrawDetailsActivity(mView.getContext(),
                                inputMoney, true, "提现成功！");
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取当前的提现限额
     */
    private void withdrawDictinary() {
        Subscription subscription = TradeModel.getInstance().withdrawDictinary()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WithdrawDictinaryOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        GlobalDialog dialog = new GlobalDialog(mView.getContext()).content("无法获取到提现配置信息！");
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialogInterface) {
                                ((Activity) mView.getContext()).finish();
                            }
                        });
                        dialog.show();
                    }

                    @Override
                    public void onNext(WithdrawDictinaryOutput dictinaryOutput) {
                        if (dictinaryOutput != null) {
                            showDataView(dictinaryOutput);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 提现配置信息
     */
    private void showDataView(WithdrawDictinaryOutput dictinaryOutput) {
        GlobalDialog dialog = new GlobalDialog(mView.getContext()).content("提现暂时无法使用！");
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                ((Activity) mView.getContext()).finish();
            }
        });
        if (!dictinaryOutput.isEnableStatus()) {
            dialog.show();
        }
        if (!DateUtils.isSupportPaymentTime(
                dictinaryOutput.getStartTime() + "," + dictinaryOutput.getEndTime())) {
            String hint = "暂时不能提现，提现时间段：(" + dictinaryOutput.getStartTime()
                    + "-" + dictinaryOutput.getEndTime() + ")。";
            dialog.setContent(hint);
            dialog.show();
        }
        mMinWithdrawLimit = dictinaryOutput.getMinMoney();
        mMaxWithdrawLimit = dictinaryOutput.getMaxMoney();

        BigDecimal tempAmount = mBalance;
        //减掉一元手续费
        BigDecimal txFee = dictinaryOutput.getWithdrawFee() == null
                ? new BigDecimal(TradeConfig.TXFEE) : dictinaryOutput.getWithdrawFee();
        if (tempAmount != null && tempAmount.subtract(txFee).compareTo(BigDecimal.ZERO) == 1) {
            mAmount = tempAmount.subtract(txFee);
        } else {
            mAmount = BigDecimal.ZERO;
        }
        mView.showTxRemarkView(dictinaryOutput.getWithdrawRemark());
        mView.showBalanceView(tempAmount, txFee);
    }

    @Override
    public void getDepositBanks() {
        final ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
        if (provider != null) {
            mView.showLoadingDialog(true);
            Subscription subscription = provider.selectUrmBankPage(CommonConfig.DEPOSIT_CARD_TYPE)
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<BankInfoOutput>>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                            mView.showErrorText(e);
                        }

                        @Override
                        public void onNext(List<BankInfoOutput> outputs) {
                            if (outputs != null && outputs.size() > 0) {
                                mView.showDepositBanks(outputs);
                            } else {
                                provider.openAddBankSetupActivity(mView.getContext(), true);
                            }
                        }
                    });
            mSubscription.add(subscription);
        }
    }

    @Override
    public TextWatcher getTextWatcher() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!resetText) {
                    Selection.getSelectionEnd(s);
                    beforeEdit = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    resetText = true;
                    CharSequence input = s.subSequence(start, start + count);
                    if (TextUtils.isEmpty(beforeEdit)) {
                        //初始为空不让输小数点
                        if (TextUtils.equals(".", input)) {
                            resetText("0.");
                        }
                    }
                    if (TextUtils.equals("0", beforeEdit)) {
                        //初始为0不让输数字
                        if (!TextUtils.isEmpty(input) && CommonUtils.isNumeric(input.toString())) {
                            resetText(input.toString());
                        }
                    }
                    String text = s.toString();
                    if (text.contains(".")) {
                        //初始包含小数点，小数点后限两位数字
                        String decimals = text.substring(text.lastIndexOf(".") + 1, text.length());
                        if (decimals.length() > 2) {
                            resetText(beforeEdit);
                        }
                    }
                    resetText = false;
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    String temp = s.toString();
                    if (TextUtils.isEmpty(temp)) return;
                    BigDecimal values = new BigDecimal(temp);
                    if (values.compareTo(mAmount) == 1) {
                        ToastUtil.showTextViewPrompt("您最多可提现" + mAmount + "元");
                        resetText(mAmount + "");
                        return;
                    }
                    if (values.compareTo(new BigDecimal(50000)) == 1) {
                        ToastUtil.showTextViewPrompt("当前最大提现金额为50000元");
                        resetText("50000");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    /**
     * 还原输入金额
     */
    private void resetText(String reset) {
        if (reset == null) reset = "";
        mView.setInputMoney(reset);
        CharSequence text = mView.getInputMoney();
        if (text != null) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
